<template>
  <view class="page">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @tap="goToSearch">
        <uni-icons type="search" size="20" color="#999"></uni-icons>
        <text class="search-placeholder">{{ searchKeyword || '搜索商品' }}</text>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view class="filter-item" 
            v-for="(filter, index) in filters" 
            :key="index"
            :class="{ 'active': currentFilter === index }"
            @tap="selectFilter(index)">
        <text class="filter-text">{{ filter.name }}</text>
        <uni-icons v-if="filter.hasArrow" 
                  :type="currentFilter === index && sortOrder === 'desc' ? 'arrowup' : 'arrowdown'" 
                  size="12" 
                  :color="currentFilter === index ? '#ff4757' : '#999'"></uni-icons>
      </view>
      <view class="filter-item" @tap="showFilterModal">
        <text class="filter-text">筛选</text>
        <uni-icons type="sound" size="14" color="#999"></uni-icons>
      </view>
    </view>

    <!-- 商品列表 -->
    <scroll-view class="product-list" 
                 scroll-y 
                 @scrolltolower="loadMore" 
                 :refresher-enabled="true"
                 :refresher-triggered="refreshing"
                 @refresherrefresh="onRefresh">
      
      <!-- 列表模式切换 -->
      <view class="view-mode">
        <view class="mode-switch">
          <view class="mode-item" 
                :class="{ 'active': viewMode === 'grid' }"
                @tap="switchViewMode('grid')">
            <uni-icons type="grid" size="16" :color="viewMode === 'grid' ? '#ff4757' : '#999'"></uni-icons>
          </view>
          <view class="mode-item" 
                :class="{ 'active': viewMode === 'list' }"
                @tap="switchViewMode('list')">
            <uni-icons type="list" size="16" :color="viewMode === 'list' ? '#ff4757' : '#999'"></uni-icons>
          </view>
        </view>
        <text class="result-count">共{{ totalCount }}件商品</text>
      </view>

      <!-- 网格模式 -->
      <view v-if="viewMode === 'grid'" class="grid-container">
        <view class="product-grid">
          <view v-for="(product, index) in productList" 
                :key="product.id" 
                class="grid-item"
                @tap="goToDetail(product.id)">
            <view class="product-image-container">
              <image class="product-image" :src="product.image" mode="aspectFill"></image>
              <view class="product-tag" v-if="product.tag">{{ product.tag }}</view>
            </view>
            <view class="product-info">
              <text class="product-title">{{ product.title }}</text>
              <view class="price-section">
                <view class="current-price">
                  <text class="price-symbol">¥</text>
                  <text class="price-value">{{ product.price }}</text>
                </view>
                <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
              </view>
              <view class="product-meta">
                <text class="sales-count">已售{{ product.sales }}</text>
                <view class="rating" v-if="product.rating">
                  <uni-icons type="star-filled" size="12" color="#FFD700"></uni-icons>
                  <text class="rating-text">{{ product.rating }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 列表模式 -->
      <view v-else class="list-container">
        <view v-for="(product, index) in productList" 
              :key="product.id" 
              class="list-item"
              @tap="goToDetail(product.id)">
          <view class="list-image-container">
            <image class="list-image" :src="product.image" mode="aspectFill"></image>
            <view class="product-tag" v-if="product.tag">{{ product.tag }}</view>
          </view>
          <view class="list-info">
            <text class="list-title">{{ product.title }}</text>
            <text class="list-subtitle" v-if="product.subtitle">{{ product.subtitle }}</text>
            <view class="list-price-section">
              <view class="current-price">
                <text class="price-symbol">¥</text>
                <text class="price-value">{{ product.price }}</text>
              </view>
              <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
            </view>
            <view class="list-meta">
              <text class="sales-count">已售{{ product.sales }}</text>
              <view class="rating" v-if="product.rating">
                <uni-icons type="star-filled" size="12" color="#FFD700"></uni-icons>
                <text class="rating-text">{{ product.rating }}</text>
              </view>
              <text class="shop-name" v-if="product.shopName">{{ product.shopName }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <uni-load-more :status="loadStatus"></uni-load-more>
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMore && productList.length > 0">
        <text class="no-more-text">没有更多商品了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="productList.length === 0 && !loading">
        <image class="empty-image" src="/static/empty-product.png" mode="aspectFit"></image>
        <text class="empty-text">暂无相关商品</text>
        <button class="retry-btn" @tap="retry">重新加载</button>
      </view>
    </scroll-view>

    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopup" type="right">
      <view class="filter-modal">
        <view class="filter-header">
          <text class="filter-title">筛选</text>
          <view class="filter-actions">
            <text class="reset-btn" @tap="resetFilter">重置</text>
            <text class="confirm-btn" @tap="confirmFilter">确定</text>
          </view>
        </view>
        
        <scroll-view class="filter-content" scroll-y>
          <!-- 价格区间 -->
          <view class="filter-section">
            <text class="section-title">价格</text>
            <view class="price-range">
              <input class="price-input" 
                     type="number" 
                     placeholder="最低价" 
                     v-model="tempFilter.minPrice">
              <text class="price-separator">-</text>
              <input class="price-input" 
                     type="number" 
                     placeholder="最高价" 
                     v-model="tempFilter.maxPrice">
            </view>
            <view class="price-tags">
              <view v-for="(range, index) in priceRanges" 
                    :key="index"
                    class="price-tag"
                    :class="{ 'selected': tempFilter.priceRange === index }"
                    @tap="selectPriceRange(index)">
                <text class="tag-text">{{ range.label }}</text>
              </view>
            </view>
          </view>
          
          <!-- 品牌 -->
          <view class="filter-section">
            <text class="section-title">品牌</text>
            <view class="brand-list">
              <view v-for="(brand, index) in brands" 
                    :key="index"
                    class="brand-item"
                    :class="{ 'selected': tempFilter.brands.includes(brand.id) }"
                    @tap="toggleBrand(brand.id)">
                <text class="brand-text">{{ brand.name }}</text>
              </view>
            </view>
          </view>
          
          <!-- 分类 -->
          <view class="filter-section">
            <text class="section-title">分类</text>
            <view class="category-list">
              <view v-for="(category, index) in categories" 
                    :key="index"
                    class="category-item"
                    :class="{ 'selected': tempFilter.categoryId === category.id }"
                    @tap="selectCategory(category.id)">
                <text class="category-text">{{ category.name }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      categoryId: '',
      viewMode: 'grid', // grid 或 list
      currentFilter: 0, // 当前选中的排序
      sortOrder: 'asc', // asc 或 desc
      filters: [
        { name: '综合', key: 'default', hasArrow: false },
        { name: '销量', key: 'sales', hasArrow: true },
        { name: '价格', key: 'price', hasArrow: true },
        { name: '评价', key: 'rating', hasArrow: true }
      ],
      productList: [],
      totalCount: 0,
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      refreshing: false,
      loadStatus: 'more', // more, loading, noMore
      
      // 筛选相关
      filterData: {
        minPrice: '',
        maxPrice: '',
        priceRange: -1,
        brands: [],
        categoryId: ''
      },
      tempFilter: {
        minPrice: '',
        maxPrice: '',
        priceRange: -1,
        brands: [],
        categoryId: ''
      },
      priceRanges: [
        { label: '0-100', min: 0, max: 100 },
        { label: '100-300', min: 100, max: 300 },
        { label: '300-500', min: 300, max: 500 },
        { label: '500-1000', min: 500, max: 1000 },
        { label: '1000以上', min: 1000, max: 999999 }
      ],
      brands: [
        { id: 1, name: '苹果' },
        { id: 2, name: '华为' },
        { id: 3, name: '小米' },
        { id: 4, name: '三星' },
        { id: 5, name: 'OPPO' },
        { id: 6, name: 'vivo' }
      ],
      categories: [
        { id: 1, name: '手机数码' },
        { id: 2, name: '电脑办公' },
        { id: 3, name: '家用电器' },
        { id: 4, name: '服饰内衣' },
        { id: 5, name: '美妆护肤' },
        { id: 6, name: '运动户外' }
      ]
    }
  },
  
  onLoad(options) {
    // 获取传入的参数
    if (options.keyword) {
      this.searchKeyword = decodeURIComponent(options.keyword)
    }
    if (options.categoryId) {
      this.categoryId = options.categoryId
      this.filterData.categoryId = options.categoryId
    }
    
    // 设置导航标题
    if (this.searchKeyword) {
      uni.setNavigationBarTitle({
        title: `搜索: ${this.searchKeyword}`
      })
    } else if (this.categoryId) {
      const category = this.categories.find(c => c.id == this.categoryId)
      if (category) {
        uni.setNavigationBarTitle({
          title: category.name
        })
      }
    } else {
      uni.setNavigationBarTitle({
        title: '商品列表'
      })
    }
    
    // 加载商品列表
    this.loadProductList()
  },
  
  methods: {
    // 加载商品列表
    async loadProductList(refresh = false) {
      if (this.loading) return
      
      this.loading = true
      this.loadStatus = 'loading'
      
      if (refresh) {
        this.currentPage = 1
        this.hasMore = true
      }
      
      try {
        // 模拟API调用
        const response = await this.mockApiCall()
        
        if (refresh) {
          this.productList = response.data
        } else {
          this.productList = [...this.productList, ...response.data]
        }
        
        this.totalCount = response.total
        this.hasMore = this.productList.length < this.totalCount
        this.currentPage++
        
      } catch (error) {
        console.error('加载商品列表失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
        this.refreshing = false
        this.loadStatus = this.hasMore ? 'more' : 'noMore'
      }
    },
    
    // 模拟API调用
    mockApiCall() {
      return new Promise((resolve) => {
        setTimeout(() => {
          const mockData = [
            {
              id: Date.now() + Math.random(),
              title: '2023新款智能手机 超清全面屏 大电量智能手机',
              subtitle: '6.7英寸OLED屏幕，5000mAh大电池',
              image: 'https://ai-public.mastergo.com/ai/img_res/0bb0de76012a21317548d7c11e047bf6.jpg',
              price: '1999',
              originalPrice: '2999',
              sales: '1.2万',
              rating: '4.8',
              tag: '限时特价',
              shopName: '官方旗舰店'
            },
            {
              id: Date.now() + Math.random() + 1,
              title: '真无线蓝牙耳机 主动降噪 通话降噪',
              subtitle: '高品质音效，长续航',
              image: 'https://ai-public.mastergo.com/ai/img_res/fa900c94f52fed4589e4b9eb9ea81fd7.jpg',
              price: '299',
              originalPrice: '499',
              sales: '8562',
              rating: '4.6',
              tag: '优惠券',
              shopName: '音频专营店'
            },
            {
              id: Date.now() + Math.random() + 2,
              title: '智能手表 心率血压监测 运动计步',
              subtitle: '健康监测，运动伴侣',
              image: 'https://ai-public.mastergo.com/ai/img_res/ffab28ea4d2c605e301b41dc31a81632.jpg',
              price: '399',
              originalPrice: '599',
              sales: '3421',
              rating: '4.7',
              tag: '新品首发',
              shopName: '智能设备店'
            },
            {
              id: Date.now() + Math.random() + 3,
              title: '超薄笔记本电脑 高性能办公本',
              subtitle: '轻薄便携，高效办公',
              image: 'https://ai-public.mastergo.com/ai/img_res/e2ad6b83b64864ad25cf6c2939f2b3c1.jpg',
              price: '4999',
              originalPrice: '6999',
              sales: '952',
              rating: '4.9',
              tag: '大额神券',
              shopName: '电脑数码店'
            }
          ]
          
          resolve({
            data: mockData,
            total: 100
          })
        }, 1000)
      })
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadProductList(true)
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.loadProductList()
      }
    },
    
    // 重试
    retry() {
      this.loadProductList(true)
    },
    
    // 切换视图模式
    switchViewMode(mode) {
      this.viewMode = mode
    },
    
    // 选择排序
    selectFilter(index) {
      if (this.currentFilter === index && this.filters[index].hasArrow) {
        // 切换排序方向
        this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
      } else {
        this.currentFilter = index
        this.sortOrder = 'asc'
      }
      
      // 重新加载数据
      this.loadProductList(true)
    },
    
    // 显示筛选弹窗
    showFilterModal() {
      // 复制当前筛选条件到临时变量
      this.tempFilter = JSON.parse(JSON.stringify(this.filterData))
      this.$refs.filterPopup.open()
    },
    
    // 选择价格区间
    selectPriceRange(index) {
      this.tempFilter.priceRange = index
      const range = this.priceRanges[index]
      this.tempFilter.minPrice = range.min.toString()
      this.tempFilter.maxPrice = range.max === 999999 ? '' : range.max.toString()
    },
    
    // 切换品牌选择
    toggleBrand(brandId) {
      const index = this.tempFilter.brands.indexOf(brandId)
      if (index > -1) {
        this.tempFilter.brands.splice(index, 1)
      } else {
        this.tempFilter.brands.push(brandId)
      }
    },
    
    // 选择分类
    selectCategory(categoryId) {
      this.tempFilter.categoryId = this.tempFilter.categoryId === categoryId ? '' : categoryId
    },
    
    // 重置筛选
    resetFilter() {
      this.tempFilter = {
        minPrice: '',
        maxPrice: '',
        priceRange: -1,
        brands: [],
        categoryId: ''
      }
    },
    
    // 确认筛选
    confirmFilter() {
      this.filterData = JSON.parse(JSON.stringify(this.tempFilter))
      this.$refs.filterPopup.close()
      this.loadProductList(true)
    },
    
    // 跳转到搜索页
    goToSearch() {
      uni.navigateTo({
        url: '/pages/search/search'
      })
    },
    
    // 跳转到商品详情
    goToDetail(productId) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${productId}`
      })
    }
  }
}
</script>

<style>
.page {
  background-color: #f5f5f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.search-bar {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.search-input {
  height: 64rpx;
  background-color: #f5f5f5;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
}

.search-placeholder {
  font-size: 28rpx;
  color: #999;
  margin-left: 10rpx;
}

.filter-bar {
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  height: 88rpx;
  border-bottom: 1px solid #f0f0f0;
}

.filter-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.filter-item.active .filter-text {
  color: #ff4757;
}

.filter-text {
  font-size: 28rpx;
  color: #333;
  margin-right: 8rpx;
}

.product-list {
  flex: 1;
}

.view-mode {
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.mode-switch {
  display: flex;
  border: 1px solid #e0e0e0;
  border-radius: 4rpx;
  overflow: hidden;
}

.mode-item {
  width: 60rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
}

.mode-item.active {
  background-color: #fff5f5;
}

.result-count {
  font-size: 24rpx;
  color: #999;
}

/* 网格模式样式 */
.grid-container {
  background-color: #fff;
  padding: 20rpx;
}

.product-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.grid-item {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  background-color: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-image-container {
  position: relative;
}

.product-image {
  width: 100%;
  height: 345rpx;
}

.product-tag {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  background-color: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
}

.product-info {
  padding: 20rpx;
}

.product-title {
  font-size: 26rpx;
  color: #333;
  line-height: 36rpx;
  height: 72rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-bottom: 10rpx;
}

.price-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 10rpx;
}

.current-price {
  display: flex;
  align-items: baseline;
  margin-right: 10rpx;
}

.price-symbol {
  font-size: 20rpx;
  color: #ff4757;
}

.price-value {
  font-size: 28rpx;
  color: #ff4757;
  font-weight: bold;
}

.original-price {
  font-size: 22rpx;
  color: #999;
  text-decoration: line-through;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sales-count {
  font-size: 22rpx;
  color: #999;
}

.rating {
  display: flex;
  align-items: center;
}

.rating-text {
  font-size: 22rpx;
  color: #999;
  margin-left: 4rpx;
}

/* 列表模式样式 */
.list-container {
  background-color: #fff;
}

.list-item {
  display: flex;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.list-image-container {
  position: relative;
  margin-right: 20rpx;
}

.list-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
}

.list-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.list-title {
  font-size: 28rpx;
  color: #333;
  line-height: 40rpx;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.list-subtitle {
  font-size: 24rpx;
  color: #666;
  line-height: 34rpx;
  margin-bottom: 10rpx;
}

.list-price-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 10rpx;
}

.list-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.shop-name {
  font-size: 22rpx;
  color: #999;
}

/* 加载状态 */
.load-more {
  padding: 30rpx;
}

.no-more {
  padding: 30rpx;
  text-align: center;
}

.no-more-text {
  font-size: 24rpx;
  color: #999;
}

.empty-state {
  padding: 100rpx 30rpx;
  text-align: center;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
  display: block;
}

.retry-btn {
  width: 200rpx;
  height: 64rpx;
  background-color: #ff4757;
  color: #fff;
  border: none;
  border-radius: 32rpx;
  font-size: 26rpx;
}

/* 筛选弹窗样式 */
.filter-modal {
  width: 600rpx;
  height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.filter-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.filter-actions {
  display: flex;
}

.reset-btn {
  font-size: 28rpx;
  color: #999;
  margin-right: 30rpx;
}

.confirm-btn {
  font-size: 28rpx;
  color: #ff4757;
}

.filter-content {
  flex: 1;
  padding: 0 30rpx;
}

.filter-section {
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.price-range {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.price-input {
  flex: 1;
  height: 64rpx;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
}

.price-separator {
  margin: 0 20rpx;
  font-size: 26rpx;
  color: #999;
}

.price-tags {
  display: flex;
  flex-wrap: wrap;
}

.price-tag {
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  padding: 15rpx 25rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
}

.price-tag.selected {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.tag-text {
  font-size: 24rpx;
  color: #333;
}

.price-tag.selected .tag-text {
  color: #ff4757;
}

.brand-list, .category-list {
  display: flex;
  flex-wrap: wrap;
}

.brand-item, .category-item {
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  padding: 15rpx 25rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
}

.brand-item.selected, .category-item.selected {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.brand-text, .category-text {
  font-size: 24rpx;
  color: #333;
}

.brand-item.selected .brand-text,
.category-item.selected .category-text {
  color: #ff4757;
}
</style>